import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, MessagePlugin, Input, Checkbox, Button, FormInstanceFunctions, SubmitContext } from 'tdesign-react';
import { LockOnIcon, UserIcon, BrowseOffIcon, BrowseIcon } from 'tdesign-icons-react';
import classnames from 'classnames';
import localforage from 'localforage';
import Style from './index.module.less';
import { LoginAPI } from '@/api/user.api';
import { useDispatch } from 'react-redux';
import { setUserInfo } from '@/modules/user';
const { FormItem } = Form;

export type ELoginType = 'password';

export default function Login() {
  const [showPsw, toggleShowPsw] = useState(false);
  const [rememberMe, setRememberMe] = useState(false);
  const formRef = useRef<FormInstanceFunctions>();
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const onSubmit = async () => {
    const formValue = formRef.current?.getFieldsValue?.(true) || {};
    const { studentId, password } = formValue;
    await LoginAPI({
      studentId,
      password,
    }).then((res) => {
      // 密码错误
      if (res.status === 202) {
        MessagePlugin.error(res.data.message)
      }
      if (res.data.status === 200) {
        MessagePlugin.success('登录成功');
        // 存储用户信息到store
        dispatch(setUserInfo(res.data));
        // 存储用户信息到indexedDB
        localforage.setItem('HIST-userInfo', res.data.data);
        // 存储token
        localStorage.setItem('HIST-token', res.data.data.token);
        // 登录成功后跳转到数据概览页面
        // navigate('/dashboard');
      } else if (res.status === 401) {
        MessagePlugin.error(res.data.message);
      }
    });

  };

  return (
    <div>
      <Form ref={formRef} className={classnames(Style.itemContainer)} labelWidth={0}>
        <FormItem name='studentId' initialData='20221514226' rules={[{ required: true, message: '账号必填', type: 'error' }]}>
          <Input size='large' placeholder='请输入学/工号：admin' prefixIcon={<UserIcon />}></Input>
        </FormItem>
        <FormItem name='password' initialData='Zjiabao@20221514226' rules={[{ required: true, message: '密码必填', type: 'error' }]}>
          <Input
            size='large'
            type={showPsw ? 'text' : 'password'}
            clearable
            placeholder='请输入登录密码：admin'
            prefixIcon={<LockOnIcon />}
            suffixIcon={
              showPsw ? (
                <BrowseIcon onClick={() => toggleShowPsw((current) => !current)} />
              ) : (
                <BrowseOffIcon onClick={() => toggleShowPsw((current) => !current)} />
              )
            }
          />
        </FormItem>
        <div className={classnames(Style.checkContainer, Style.rememberPwd)}>
          <Checkbox checked={rememberMe} onChange={(checked) => setRememberMe(checked)}>30天内免登录</Checkbox>
          <span className={Style.checkContainerTip}>忘记密码？</span>
        </div>
        {
          <FormItem className={Style.btnContainer}>
            <Button block size='large' onClick={onSubmit}>
              登录
            </Button>
          </FormItem>
        }
      </Form>
    </div >
  );
}
